/** <a href="http://www.cpupk.com/decompiler">Eclipse Class Decompiler</a> plugin, Copyright (c) 2017 Chen Chao. **/
package com.minierp.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.minierp.bean.StafferBean;
import com.minierp.bean.UserBean;
import com.minierp.bean.UserStatus;
import com.minierp.dao.CodeRuleDao;
import com.minierp.dao.DepartmentDao;
import com.minierp.dao.IdGenerator;
import com.minierp.dao.SerialNumberDao;
import com.minierp.dao.StafferDao;
import com.minierp.dao.UserDao;
import com.minierp.err.PermissionDennyException;
import com.minierp.helper.EncCommonHelper;
import com.minierp.helper.EncInterceptorHelper;
import com.minierp.helper.PageHelper;
import com.minierp.model.CodeRule;
import com.minierp.model.Department;
import com.minierp.model.Staffer;
import com.minierp.view.InnerPbListExcelView;
import com.minierp.view.StafferListExcelView;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class StafferMACtr extends MultiActionController {
	private StafferDao stafferDao;
	private DepartmentDao departmentDao;
	private UserDao userDao;
	private CodeRuleDao codeRuleDao;
	private SerialNumberDao serialNumberDao;
	private IdGenerator idGenerator;
	private String mainView;
	private String listView;
	private String mainForSelectView;
	private String listForSelectView;
	private String listForMultiSelectView;
	private String innerPbMainView;
	private String innerPbListView;
	private String impoFormView;

	public String getImpoFormView() {
		return this.impoFormView;
	}

	public void setImpoFormView(String impoFormView) {
		this.impoFormView = impoFormView;
	}

	public String getInnerPbMainView() {
		return this.innerPbMainView;
	}

	public void setInnerPbMainView(String innerPbMainView) {
		this.innerPbMainView = innerPbMainView;
	}

	public String getInnerPbListView() {
		return this.innerPbListView;
	}

	public void setInnerPbListView(String innerPbListView) {
		this.innerPbListView = innerPbListView;
	}

	public ModelAndView handleMain(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		if (!EncCommonHelper.checkPrivilege(request, "BASE_STAF")) {
			throw new PermissionDennyException("Permission Denny");
		} else {
			ModelAndView mv = new ModelAndView(this.mainView);
			return mv;
		}
	}

	public ModelAndView handleList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String contentType = request.getParameter("content_type");
		Map map = this.getStafferList(request, false, true, true, "CODE");
		if (contentType != null && contentType.equals("EXCEL")) {
			StafferListExcelView mv2 = new StafferListExcelView();
			ModelAndView mv1 = new ModelAndView(mv2, map);
			return mv1;
		} else {
			ModelAndView mv = new ModelAndView(this.listView);
			mv.addAllObjects(map);
			return mv;
		}
	}

	public ModelAndView handleInnerPbMain(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.innerPbMainView);
		return mv;
	}

	public ModelAndView handleInnerPbList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String contentType = request.getParameter("content_type");
		Map map = this.getStafferList(request, true, false, true, "CODE");
		if (contentType != null && contentType.equals("EXCEL")) {
			InnerPbListExcelView mv2 = new InnerPbListExcelView();
			ModelAndView mv1 = new ModelAndView(mv2, map);
			return mv1;
		} else {
			ModelAndView mv = new ModelAndView(this.innerPbListView);
			mv.addAllObjects(map);
			return mv;
		}
	}

	public ModelAndView handleDelete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnUrl = request.getParameter("from_url");
		String id = request.getParameter("id");
		ModelAndView mv = new ModelAndView("redirect:" + returnUrl);
		if (EncCommonHelper.checkPrivilege(request, "BASE_STAF")
				&& Long.parseLong(id) != -1L) {
			if (this.stafferDao.isHasClient(Long.parseLong(id))) {
				Staffer s = (Staffer) this.stafferDao.get(Staffer.class,
						Long.parseLong(id));
				if (s != null) {
					EncCommonHelper.setAlertMessage(request,
							"请进入客户移交，将 " + s.getStafferName()
									+ " 的客户移交给其他人后，才能删除 " + s.getStafferName()
									+ "！");
				}
			} else {
				this.stafferDao.delete(Long.parseLong(id));
				this.userDao.deleteStafferUser(Long.parseLong(id));
				EncCommonHelper.setAlertMessage(request, "删除成功！");
			}

			return mv;
		} else {
			throw new Exception("Permission deny!");
		}
	}

	public ModelAndView handlePause(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String returnUrl = request.getParameter("from_url");
		String id = request.getParameter("id");
		ModelAndView mv = new ModelAndView("redirect:" + returnUrl);
		if (EncCommonHelper.checkPrivilege(request, "BASE_STAF")
				&& Long.parseLong(id) != -1L) {
			Staffer s = (Staffer) this.stafferDao.get(Staffer.class,
					Long.parseLong(id));
			if (s != null) {
				s.setEnabled("N");
				this.stafferDao.update(s);
				this.userDao.unenabledStafferUser(s.getId());
			}

			EncCommonHelper.setAlertMessage(request, "设置成功！");
			return mv;
		} else {
			throw new Exception("Permission deny!");
		}
	}

	public ModelAndView handleMainForSelect(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(this.mainForSelectView);
		mv.addObject("type", request.getParameter("type"));
		return mv;
	}

	public ModelAndView handleListForSelect(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String type = request.getParameter("type");
		ModelAndView mv;
		if (type != null && type.equals("MULTI")) {
			mv = new ModelAndView(this.listForMultiSelectView);
		} else {
			mv = new ModelAndView(this.listForSelectView);
		}

		mv.addAllObjects(this
				.getStafferList(request, true, false, true, "CODE"));
		mv.addObject("type", type);
		return mv;
	}

	private Map getStafferList(HttpServletRequest request, boolean justEnabled,
			boolean parseSuperior, boolean includeSub, String orderBy)
			throws Exception {
		HashMap map = new HashMap();
		String departmentId = request.getParameter("department_id");
		String searchKey = request.getParameter("search_key");
		String searchAll = request.getParameter("search_all");
		if (departmentId != null && !departmentId.equals("")) {
			map.put("department",
					this.departmentDao.get(Department.class,
							Long.parseLong(departmentId)));
		} else {
			searchAll = "1";
		}

		List list;
		if (searchAll != null && searchAll.equals("1")) {
			list = this.stafferDao.getList(0L, justEnabled, includeSub,
					searchKey, orderBy);
		} else {
			list = this.stafferDao.getList(Long.parseLong(departmentId),
					justEnabled, includeSub, searchKey, orderBy);
		}

		ArrayList arr = new ArrayList();
		List depList = this.departmentDao.getList(false);
		int enabledCount = 0;
		int unenabledCount = 0;

		for (int i = 0; i < list.size(); ++i) {
			StafferBean b = new StafferBean();
			Staffer s = (Staffer) list.get(i);
			if (s.getEnabled().equals("Y")) {
				++enabledCount;
			} else {
				++unenabledCount;
			}

			b.setStaffer(s);
			if (parseSuperior && s.getSuperiorId() != 0L) {
				Staffer superior = (Staffer) this.stafferDao.get(Staffer.class,
						s.getSuperiorId());
				if (superior != null) {
					b.setSuperiorName(superior.getStafferName());
				}
			}

			b.setDepName(EncCommonHelper.getSimpleObjectName(depList,
					s.getDepartmentId()));
			arr.add(b);
		}

		map.put("unenabledCount", String.valueOf(unenabledCount));
		map.put("enabledCount", String.valueOf(enabledCount));
		map.put("stafferList", arr);
		map.put("departmentId", departmentId);
		map.put("searchKey", searchKey);
		map.put("searchAll", searchAll);
		return map;
	}

	public ModelAndView handleImpoForm(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return new ModelAndView(this.impoFormView);
	}

	public ModelAndView handleImpo(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fileName = request.getParameter("file_name");
		File file = new File(this.getServletContext().getRealPath(fileName));
		String alertMsg = "";
		List depList = this.departmentDao.getList(true);
		HashMap depMap = new HashMap();
		CodeRule stafCr = this.codeRuleDao.get("STAFFER");
		CodeRule depCr = this.codeRuleDao.get("DEPARTMENT");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
		BufferedInputStream in = null;

		try {
			in = new BufferedInputStream(new FileInputStream(file));
			HSSFWorkbook out = new HSSFWorkbook(new POIFSFileSystem(in));
			int count = 0;

			for (int str = 0; str < out.getNumberOfSheets(); ++str) {
				HSSFSheet hssfsheet = out.getSheetAt(str);

				for (int j = 1; j < hssfsheet.getPhysicalNumberOfRows(); ++j) {
					HSSFRow hssfrow = hssfsheet.getRow(j);
					if (hssfrow == null) {
						break;
					}

					boolean hasInput = false;
					HSSFCell cell = hssfrow.getCell(0);
					String stafCode = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(stafCode);
					cell = hssfrow.getCell(1);
					String depName = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(depName);
					cell = hssfrow.getCell(2);
					String poss = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(poss);
					cell = hssfrow.getCell(3);
					String stafName = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(stafName);
					cell = hssfrow.getCell(4);
					String inDateStr = PageHelper.getCellVal(cell, 20);
					hasInput = hasInput || !PageHelper.isEmpty(inDateStr);
					cell = hssfrow.getCell(5);
					String sex = PageHelper.getCellVal(cell, 10);
					hasInput = hasInput || !PageHelper.isEmpty(sex);
					cell = hssfrow.getCell(6);
					String birt = PageHelper.getCellVal(cell, 20);
					hasInput = hasInput || !PageHelper.isEmpty(birt);
					cell = hssfrow.getCell(7);
					String orig = PageHelper.getCellVal(cell, 10);
					hasInput = hasInput || !PageHelper.isEmpty(orig);
					cell = hssfrow.getCell(8);
					String hous = PageHelper.getCellVal(cell, 10);
					hasInput = hasInput || !PageHelper.isEmpty(hous);
					cell = hssfrow.getCell(9);
					String phon = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(phon);
					cell = hssfrow.getCell(10);
					String subPhon = PageHelper.getCellVal(cell, 10);
					hasInput = hasInput || !PageHelper.isEmpty(subPhon);
					cell = hssfrow.getCell(11);
					String qq = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(qq);
					cell = hssfrow.getCell(12);
					String mobi = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(mobi);
					cell = hssfrow.getCell(13);
					String subMobi = PageHelper.getCellVal(cell, 15);
					hasInput = hasInput || !PageHelper.isEmpty(subMobi);
					cell = hssfrow.getCell(14);
					String emai = PageHelper.getCellVal(cell, 50);
					hasInput = hasInput || !PageHelper.isEmpty(emai);
					cell = hssfrow.getCell(15);
					String mark = PageHelper.getCellVal(cell, 100);
					hasInput = hasInput || !PageHelper.isEmpty(mark);
					if (hasInput) {
						long depId = 0L;
						String depCode = "";
						boolean dataOk = true;
						Staffer inDate;
						if (dataOk) {
							if (stafCode != null && !stafCode.equals("")) {
								inDate = this.stafferDao.get(stafCode);
								if (inDate != null) {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j + "行：员工编号已经存在！");
									dataOk = false;
								}
							} else if (!stafCr.getGenerateRule().equals(
									"MANUAL")) {
								stafCode = PageHelper.generateCode(
										this.serialNumberDao, stafCr, "", 0L);

								for (inDate = this.stafferDao.get(stafCode); inDate != null; inDate = this.stafferDao
										.get(stafCode)) {
									stafCode = PageHelper.generateCode(
											this.serialNumberDao, stafCr, "",
											0L);
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：员工编号规则必须设置为自动产生！");
								dataOk = false;
							}
						}

						if (dataOk) {
							if (depName != null && !depName.equals("")) {
								for (int arg58 = 0; arg58 < depList.size(); ++arg58) {
									Department birthday = (Department) depList
											.get(arg58);
									if (birthday.getDepartmentName().equals(
											depName)) {
										depId = birthday.getId();
										break;
									}
								}

								if (depId == 0L && depMap.containsKey(depName)) {
									depId = ((Long) depMap.get(depName))
											.longValue();
								}

								if (depId == 0L) {
									if (!depCr.getGenerateRule().equals(
											"MANUAL")) {
										depCode = PageHelper.generateCode(
												this.serialNumberDao, depCr,
												"", 0L);

										for (Department arg60 = this.departmentDao
												.get(depCode); arg60 != null; arg60 = this.departmentDao
												.get(depCode)) {
											depCode = PageHelper.generateCode(
													this.serialNumberDao,
													stafCr, "", 0L);
										}
									} else {
										alertMsg = PageHelper.appendAlertMsg(
												alertMsg, "第" + j
														+ "行：部门编号规则必须设置为自动产生！");
										dataOk = false;
									}
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：部门名称不能为空！");
								dataOk = false;
							}
						}

						if (dataOk) {
							if (stafName != null && !stafName.equals("")) {
								inDate = this.stafferDao.getByName(stafName);
								if (inDate != null) {
									alertMsg = PageHelper.appendAlertMsg(
											alertMsg, "第" + j + "行：姓名已经存在！");
									dataOk = false;
								}
							} else {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：姓名不能为空！");
								dataOk = false;
							}
						}

						Date arg62 = null;
						if (dataOk && inDateStr != null
								&& !inDateStr.equals("")) {
							try {
								arg62 = sf.parse(inDateStr);
							} catch (Exception arg53) {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：入职日期格式错误！");
								dataOk = false;
							}
						}

						Date arg59 = null;
						if (dataOk && birt != null && !birt.equals("")) {
							try {
								arg59 = sf.parse(birt);
							} catch (Exception arg52) {
								alertMsg = PageHelper.appendAlertMsg(alertMsg,
										"第" + j + "行：生日格式错误！");
								dataOk = false;
							}
						}

						if (dataOk) {
							if (sex != null && sex.equals("女")) {
								sex = "FEMALE";
							} else {
								sex = "MAN";
							}

							if (depId == 0L) {
								Department s = new Department();
								s.setDepartmentCode(depCode);
								s.setDepartmentName(depName);
								s.setId(this.idGenerator.getId(Department.class
										.getName()));
								this.departmentDao.save(s);
								depId = s.getId();
								depMap.put(depName, Long.valueOf(depId));
							}

							Staffer arg61 = new Staffer();
							arg61.setBirthday(arg59);
							arg61.setDepartmentId(depId);
							arg61.setEmail(emai);
							arg61.setHousehold(hous);
							arg61.setId(this.idGenerator.getId(Staffer.class
									.getName()));
							arg61.setInDate(arg62);
							arg61.setMark(mark);
							arg61.setMobile(mobi);
							arg61.setNameSpell(PageHelper.getPinYinHeadChar(
									stafName).toUpperCase());
							arg61.setOrigin(orig);
							arg61.setPhone(phon);
							arg61.setPossie(poss);
							arg61.setQq(qq);
							arg61.setSex(sex);
							arg61.setStafferCode(stafCode);
							arg61.setStafferName(stafName);
							arg61.setSubMobile(subMobi);
							arg61.setSubPhone(subPhon);
							this.stafferDao.save(arg61);
							++count;
						}
					}
				}
			}

			String arg57 = "<B>成功导入" + count + "行</B>";
			if (alertMsg != null && !alertMsg.equals("")) {
				alertMsg = PageHelper.appendAlertMsg(arg57, alertMsg);
			} else {
				alertMsg = arg57;
			}
		} catch (Exception arg54) {
			alertMsg = "导入错误：" + arg54.getMessage();
		} finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception arg51) {
				;
			}

		}

		EncCommonHelper.setAlertMessage(request, alertMsg);
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ServletOutputStream arg56 = response.getOutputStream();
		arg56.write("OK".getBytes());
		arg56.flush();
		arg56.close();
		return null;
	}

	public ModelAndView handleAppList(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HashMap map = new HashMap();
		UserStatus s = EncInterceptorHelper.checkAppUserSignon(request);
		UserBean ub = s.getUserBean();
		String json;
		if (ub == null) {
			map.put("status", "NO_LOGIN");
			map.put("errMsg", "");
		} else {
			try {
				String mapper = request.getParameter("staf_name");
				json = request.getParameter("depa_name");
				String out = request.getParameter("orde");
				int total = this.stafferDao.getAppListForSelectCount(mapper,
						json);
				int perPageNum = EncCommonHelper.getPageSize(request);
				int pageno = EncCommonHelper.getCurrentPageIndex(request,
						total, perPageNum);
				if (total > pageno * perPageNum) {
					map.put("more", "Y");
				} else {
					map.put("more", "N");
				}

				List list = this.stafferDao.getAppListForSelect(mapper, json,
						out, (pageno - 1) * perPageNum, perPageNum);
				ArrayList items = new ArrayList();

				for (int i = 0; i < list.size(); ++i) {
					Object[] objs = (Object[]) list.get(i);
					HashMap item = new HashMap();
					item.put("id", objs[0]);
					item.put("stafName", objs[1]);
					item.put("depaName", PageHelper.parseNull((String) objs[2]));
					items.add(item);
				}

				map.put("items", items);
				map.put("status", "OK");
				map.put("errMsg", "");
			} catch (Exception arg16) {
				map.put("status", "ERROR");
				map.put("errMsg", arg16.toString());
			}
		}

		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Pragma", "no-cache");
		ObjectMapper arg17 = new ObjectMapper();
		json = arg17.writeValueAsString(map);
		ServletOutputStream arg18 = response.getOutputStream();
		arg18.write(json.getBytes("utf-8"));
		arg18.flush();
		arg18.close();
		return null;
	}

	public DepartmentDao getDepartmentDao() {
		return this.departmentDao;
	}

	public void setDepartmentDao(DepartmentDao departmentDao) {
		this.departmentDao = departmentDao;
	}

	public String getListView() {
		return this.listView;
	}

	public void setListView(String listView) {
		this.listView = listView;
	}

	public String getMainView() {
		return this.mainView;
	}

	public void setMainView(String mainView) {
		this.mainView = mainView;
	}

	public StafferDao getStafferDao() {
		return this.stafferDao;
	}

	public void setStafferDao(StafferDao stafferDao) {
		this.stafferDao = stafferDao;
	}

	public String getListForSelectView() {
		return this.listForSelectView;
	}

	public void setListForSelectView(String listForSelectView) {
		this.listForSelectView = listForSelectView;
	}

	public String getMainForSelectView() {
		return this.mainForSelectView;
	}

	public void setMainForSelectView(String mainForSelectView) {
		this.mainForSelectView = mainForSelectView;
	}

	public String getListForMultiSelectView() {
		return this.listForMultiSelectView;
	}

	public void setListForMultiSelectView(String listForMultiSelectView) {
		this.listForMultiSelectView = listForMultiSelectView;
	}

	public UserDao getUserDao() {
		return this.userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public CodeRuleDao getCodeRuleDao() {
		return this.codeRuleDao;
	}

	public void setCodeRuleDao(CodeRuleDao codeRuleDao) {
		this.codeRuleDao = codeRuleDao;
	}

	public SerialNumberDao getSerialNumberDao() {
		return this.serialNumberDao;
	}

	public void setSerialNumberDao(SerialNumberDao serialNumberDao) {
		this.serialNumberDao = serialNumberDao;
	}

	public IdGenerator getIdGenerator() {
		return this.idGenerator;
	}

	public void setIdGenerator(IdGenerator idGenerator) {
		this.idGenerator = idGenerator;
	}
}